import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import {logger, httpLogger} from './config/logger.js';
import fs from 'fs';
import yaml from 'js-yaml';
import apiRoutes from './routers/apiRoutes.js';

// 读取 YAML 配置文件
const config = yaml.load(fs.readFileSync('./src/application.yaml', 'utf8'));

const app = express();

// 中间件配置
const setupMiddlewares = () => {
    app.use(cors());
    app.use(express.json());
    app.use(morgan('short', {stream: {write: message => httpLogger.info(message.trim())}}));

};

// 路由配置
const setupRoutes = () => {
    app.use('/api', apiRoutes);
};

// 服务器启动函数
const startServer = async () => {
    const PORT = config.server.port || 9999;
    app.listen(PORT, () => {
        logger.info(`服务器已启动 端口: ${PORT}`);
    });
};

// 初始化应用
const initializeApp = async () => {
    setupMiddlewares();
    setupRoutes();
    await startServer();
};

// 启动应用
initializeApp()
    .then(() => {
        logger.info('应用初始化成功。');
    })
    .catch((error) => {
        logger.error('应用初始化失败:', error);
        process.exit(1);
    });

export default app;
